﻿using ECMS.AppService.Model.Models;
using ECMS.AppService.Model.Requests.AppUser;
using ECMS.AppService.Model.Responses;
using ECMS.Domain.Models;
using ECMS.Infrastructure.ClientData;
using ECMS.Infrastructure.Const;
using ECMS.Infrastructure.Domain;
using ECMS.Infrastructure.Extensions;
using ECMS.Infrastructure.Helper;
using Microsoft.EntityFrameworkCore;
using QuestionBank.Infrastructure.Helper;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace ECMS.AppService.Implements
{
    /// <summary>
    /// 管理员服务
    /// </summary>
    public partial class AppUserService
    {
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<ApiResult<SaveResponse>> SaveAsync(AppUserModel model)
        {
            var response = new ApiResult<SaveResponse>
            {
                StatusCode = 200
            };
            try
            {
                if (model == null)
                    throw new ArgumentNullException(nameof(model));
                AppUser entity;
                if (model.Guid == null)
                {
                    // 手机号唯一检查
                    if (Query().Any(p => p.Mobile == model.Mobile))
                    {
                        response.Message = "手机号已存在,请更改.";
                        return response;
                    }

                    entity = new AppUser
                    {
                        LoginName = model.LoginName,
                        Password = CryptoHelper.DESEncrypt(model.Password),
                        Mobile = model.Mobile,
                        RealName = model.RealName,
                        IsLock = model.IsLock,
                    };

                    await _unitofwork.RegisterNewAsync(entity);
                }
                else
                {
                    // 用户名唯一检查
                    if (Query().Any(p => p.LoginName == model.LoginName && p.Guid != model.Guid))
                    {
                        response.Message = "登录已存在,请更改.";
                        return response;
                    }
                    // 手机号唯一检查
                    if (Query().Any(p => p.Mobile == model.Mobile && p.Guid != model.Guid))
                    {
                        response.Message = "手机号已存在,请更改.";
                        return response;
                    }

                    entity = await Query().Where(p => p.Guid == model.Guid).FirstOrDefaultAsync();
                    if (entity == null)
                    {
                        response.Message = "找不到该用户信息，更新失败.";
                        return response;
                    }
                    entity.LoginName = model.LoginName;
                    if (entity.Password != model.Password)
                        entity.Password = CryptoHelper.DESEncrypt(model.Password);
                    entity.Mobile = model.Mobile;
                    entity.RealName = model.RealName;
                    entity.IsLock = model.IsLock;

                    _unitofwork.RegisterDirty(entity);
                }
                var flag = await _unitofwork.CommitAsync();
                response.Success = flag;
                response.Message = flag ? "保存成功." : "保存失败.";

            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
                response.StatusCode = 500;
            }

            return response;
        }
        /// <summary>
        /// 查看客户
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<ApiResult<Page<AppUserResponse>>> GetPagesAsync(GetAppUserPagesRequest request)
        {
            var response = new ApiResult<Page<AppUserResponse>>
            {
                StatusCode = 200
            };
            try
            {
                if (request == null)
                    throw new ArgumentNullException(nameof(request));
                var result = await Query()
                    .HasWhere(request.LoginName, p => p.LoginName.Contains(request.LoginName))
                    .HasWhere(request.Mobile, p => p.Mobile.Contains(request.Mobile))
                    .OrderByDescending(p => p.Id)
                    .ToPageAsync(request.PageIndex, request.PageSize);

                var flag = result.Items != null && result.Items.Count > 0;
                response.Success = flag;
                response.Message = flag ? "获取成功." : "暂无数据.";

                if (flag)
                {
                    response.Data = result.ToViewPage(u => new AppUserResponse
                    {
                        LoginName = u.LoginName,
                        Mobile = u.Mobile,
                        Guid = u.Guid,
                        Id = u.Id,
                        Password = u.Password,
                        RealName = u.RealName,
                        CreateTime = u.CreateTime,
                        IsLock = u.IsLock,
                        LockTime = u.LockTime,
                        UnLockTime = u.UnLockTime

                    });
                }

            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
                response.StatusCode = 500;
            }

            return response;
        }
        /// <summary>
        /// 查看客户详细
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        public async Task<AppUserResponse> GetDetailAsync(Guid guid)
        {
            var u = await Query().FirstOrDefaultAsync(p => p.Guid == guid);
            if (u == null)
                return new AppUserResponse();
            return new AppUserResponse
            {
                Guid = u.Guid,
                Id = u.Id,
                LoginName = u.LoginName,
                Mobile = u.Mobile,
                Password = u.Password,
                RealName = u.RealName,
                IsLock = u.IsLock,
                LoginIP = u.LoginIP,
                Signature = u.Signature,
                LastLoginTime = u.LastLoginTime,
                LastChangeTime = u.LastChangeTime,
                Sex = u.Sex,
                BirthDay = u.BirthDay,
                Email = u.Email,
                IdCard = u.IdCard,
                CreateTime = u.CreateTime,
                Remark = u.Remark
            };
        }
        /// <summary>
        /// 查看客户详细
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ForumUserResponse> GetDetailAsync(int id)
        {
            var u = await Query().FirstOrDefaultAsync(p => p.Id == id);
            if (u == null)
                return new ForumUserResponse();
            return new ForumUserResponse
            {
                Guid = u.Guid,
                LoginName = u.LoginName,
                Mobile = u.Mobile,
                //Password = u.Password,
                RealName = u.RealName,
                //IsLock = u.IsLock,
                LoginIP = u.LoginIP,
                Signature = u.Signature,
                //LastLoginTime = u.LastLoginTime,
                //LastChangeTime = u.LastChangeTime,
                Sex = u.Sex,
                //BirthDay = u.BirthDay,
                Email = u.Email,
                //IdCard = u.IdCard,
                //CreateTime = u.CreateTime,
                //Remark = u.Remark
            };
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        public async Task<ApiResult<string>> DeleteAsync(Guid? guid)
        {
            var response = new ApiResult<string>
            {
                StatusCode = 200
            };
            try
            {
                if (guid == null)
                    throw new ArgumentNullException(nameof(guid));
                // 物理删除
                Delete(p => p.Guid == guid);

                var flag = await _unitofwork.CommitAsync();
                response.Success = flag;
                response.Message = flag ? "移除成功." : "移除失败.";
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
                response.StatusCode = 500;
            }

            return response;
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<ApiResult<AppUserResponse>> LoginAsync(LoginRequest request)
        {
            var response = new ApiResult<AppUserResponse>();
            try
            {
                // 读取用户信息
                var entity = await Query().FirstOrDefaultAsync(p => p.LoginName == request.LoginName || p.Mobile == request.LoginName);
                if (entity == null)
                {
                    response.Message = "用户不存在.";
                    return response;
                }
                if (entity.Password != CryptoHelper.DESEncrypt(request.Password))
                {
                    response.Message = "用户名或密码错误.";
                    return response;
                }
                if (entity.IsLock && entity.LockTime > DateTime.Now)
                {
                    response.Message = $"帐号已锁定,于{entity.UnLockTime.ToString("yyyy-MM-dd HH:mm:ss")}自动解锁.";
                    return response;
                }

                if (entity.IsLock)
                {
                    entity.IsLock = false;// 帐号解除锁定
                    _unitofwork.RegisterDirty(entity);
                    await _unitofwork.CommitAsync();
                }
                response.Success = true;
                response.Message = "验证成功.";
                response.Data = new AppUserResponse
                {
                    Guid = entity.Guid,
                    Id = entity.Id,
                    LoginName = entity.LoginName,
                    Mobile = entity.Mobile,
                    RealName = entity.RealName,
                    HeadImg = entity.HeadImg,
                    Signature = entity.Signature,
                    LoginIP = entity.LoginIP,
                    LastLoginTime = entity.LastLoginTime,
                    LastChangeTime = entity.LastChangeTime,
                    Sex = entity.Sex,
                    BirthDay = entity.BirthDay,
                    Email = entity.Email,
                    IdCard = entity.IdCard,
                    CreateTime = entity.CreateTime,
                    Remark = entity.Remark
                };
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
                response.StatusCode = 500;
            }
            return response;
        }
        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<ApiResult<AppUserResponse>> RegisterAsync(RegisterRequest request)
        {
            var response = new ApiResult<AppUserResponse>();

            if (!VerificationHelper.IsMobilePhoneNumber(request.Mobile))
            {
                response.Message = "手机号格式不正确";
                response.StatusCode = -1;
                return response;
            }

            try
            {
                // 读取用户信息
                var entity = await Query().FirstOrDefaultAsync(p => p.Mobile == request.Mobile);

                if (entity != null)
                {
                    response.Message = "手机号已注册";
                    response.StatusCode = -2;
                    return response;
                }
                entity = new AppUser();
                entity.Code = request.Code;
                entity.Mobile = request.Mobile;
                entity.CreateTime = DateTime.Now;
                entity.LoginName = request.Mobile;
                entity.RealName = "用户_" + request.Mobile;
                entity.LastChangeTime = DateTime.Now;
                entity.Password = CryptoHelper.DESEncrypt(request.Password);
                entity.HeadImg = Const.defaultHeadImgUrl;

                _unitofwork.RegisterNew(entity);

                var flag = await _unitofwork.CommitAsync();
                response.Success = flag;
                response.Message = flag ? "注册成功." : "注册失败.";
                response.Data = new AppUserResponse
                {
                    Guid = entity.Guid,
                    Id = entity.Id,
                    Mobile = entity.Mobile,
                    RealName = entity.RealName,
                    LoginName = entity.Mobile,
                    Password = entity.Password,
                    CreateTime = entity.CreateTime
                };
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
                new Logger("注册错误").Error(ex.Message);
                response.StatusCode = 500;
            }
            return response;
        }


        /// <summary>
        /// 更新用户最后登录时间
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task<ApiResult<AppUserResponse>> UpdateLastLoginTime(Guid? guid)
        {
            var response = new ApiResult<AppUserResponse>();

            if (!guid.HasValue)
            {
                response.Message = "更新用户登录时间失败.";
                response.StatusCode = -1;
                return response;
            }

            try
            {
                // 读取用户信息
                var entity = await Query().FirstOrDefaultAsync(p => p.Guid == guid);
                if (entity == null)
                {
                    response.Message = "用户不存在.";
                    response.StatusCode = -2;
                    return response;
                }
                entity.LastLoginTime = DateTime.Now;

                _unitofwork.RegisterDirty(entity);

                var flag = await _unitofwork.CommitAsync();
                response.Success = flag;
                response.Message = flag ? "更新成功." : "更新失败.";
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
                response.StatusCode = 500;
            }
            return response;
        }

        public async Task<bool> CheckUser(string loginname, string password)
        {
            var entity = await Query().FirstOrDefaultAsync(p => p.LoginName == loginname);
            if (entity == null) return false;
            return entity.Password == CryptoHelper.DESEncrypt(password);
        }
    }
}
